<template>
    <div>
        <el-button type="primary" v-if="noticeActive" @click="addBrash" id="notice-btn-brash">选择施工道路</el-button>
        <el-button type="primary" v-if="noticeActive & haveEffectArea" @click="dialogVisible = true"
            id="notice-btn-show-dialog">编辑公告</el-button>
        <el-dialog v-model="dialogVisible" title="公告信息" width="30%" draggable id="notice-dialog">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <span>发布公告的区域与物业电话</span>
                    </div>
                </template>
                <el-input v-model="keyword" class="w-50 m-2" @keyup.enter="getBlock(true)" placeholder="Type something"
                    :prefix-icon="Search" />
                <el-table :data="effectBlockPage" border style="width: 100%">
                    <el-table-column prop="name" label="区域名称" />
                    <el-table-column prop="tel" label="物业电话" />
                </el-table>
                <el-pagination layout="prev, pager, next" :total="total" @current-change="handelCurrentChange" />
                <el-form-item label="公告内容">
                    <el-input v-model="notice" type="textarea" />
                </el-form-item>
            </el-card>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="addNotice">
                        发送
                    </el-button>
                    <el-button @click="dialogVisible = false">隐藏</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { useMenuStore } from '../../store';
import { createDraw, getFeaturePosition } from '../../utils/createDraw'
import { query, queryVectorLayer } from '../../utils/query'
import * as turf from '@turf/turf'
import { getCurentTime, getCurrentTime } from '../../utils/index'
import { Search } from '@element-plus/icons-vue'
import { sendNotice } from '../../api/index'
let menuStore = useMenuStore()
let noticeActive = ref(false)
let haveEffectArea = ref(false)
let dialogVisible = ref(false)

watch(() => menuStore.activeIndex, val => {
    if (val === '5') {
        init()
    } else {
        noticeActive.value = false
        finish()
        map.removeInteraction(brash)
    }
})
const source = new ol.source.Vector({})
const layer = new ol.layer.Vector({
    source,
    opacity: 1,
    zIndex: 99,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#1046ff',
            width: 4
        })
    }),
    fill: new ol.style.Fill({
        color: '#1046ff'
    })

})
const brash = createDraw({ source, type: 'LineString' })
brash.on('drawend', handleDrawend)
let bufferFeature = null
let map = null

onMounted(() => {
    map = inject('$map')
})
function handleDrawend(e) {
    map.removeInteraction(brash)
    drawBuffer(e)
    clip()
}
function init() {
    noticeActive.value = true
    map.getView().animate({
        center: [114.395, 30.495],
        zoom: 15
    })
    map.addLayer(layer)
}
function addBrash() {
    source.clear()
    if (anaLayer) map.removeLayer(anaLayer)
    haveEffectArea.value = false
    map.addInteraction(brash)
}
function finish() {
    source.clear()
    notice.value = ''
    keyword.value = ''
    map.removeLayer(layer)
}

async function drawBuffer(e) {
    const coordinates = getFeaturePosition(e.feature)
    const line = turf.lineString(coordinates)
    const feature = turf.buffer(line, 0.1)
    bufferFeature = new ol.format.GeoJSON().readFeatures(feature)
    source.addFeatures(bufferFeature)
}



let featureSet = null
let effectBlocksAll = ref([])
let total = ref(0)
let anaLayer = null
function clip() {
    const geo = bufferFeature[0].getGeometry()
    let strPos = geo.flatCoordinates.join(',')
    clipByPolyAnalysis(strPos)
}
function getBlock(isSearch) {
    let payload = { url: resultLayerUrl, success: querySuccess }
    if (isSearch) {
        payload.attr = {
            key: 'name',
            value: keyword.value
        }
    }
    queryVectorLayer(payload)
}
function querySuccess(e) {
    featureSet = e
    effectBlocksAll.value = []
    effectBlockPage.value = []
    total.value = e.TotalCount
    if (e.TotalCount === 0) {
        haveEffectArea.value = false
        ElMessageBox.confirm(
            '没有影响小区，请重新绘制施工道路',
            {
                confirmButtonText: 'OK',
                showCancelButton: false,
                showClose: false,
                type: 'warning',
            }
        )
            .then(() => {
                finish()
            })
    } else {
        haveEffectArea.value = true
        e.SFEleArray.forEach((item, index) => {
            let block = {
                name: item.AttValue[4],
                tel: item.AttValue[5]
            }
            if (index < 5) {
                effectBlockPage.value.push(block)
            }
            effectBlocksAll.value.push(block)

        })
        dialogVisible.value = true
    }


}

let notice = ref('')
let keyword = ref('')
async function addNotice() {
    const noticeData = {
        content: notice.value,
        area: effectBlocksAll.value.map(item => item.name).join(','),
        time: getCurrentTime()
    }
    // 获取现有公告数据
    let notices = JSON.parse(localStorage.getItem('notices') || '[]')
    // 添加新公告
    notices.push(noticeData)
    // 保存到localStorage
    localStorage.setItem('notices', JSON.stringify(notices))
    ElMessage({
        message: '发布成功',
        type: 'success',
    })
    clear()
}
function clear() {
    // 清空 公告栏，finish, 关闭
    finish()
    haveEffectArea.value = false
    dialogVisible.value = false
}

let effectBlockPage = ref([])
let page = {
    pageIndex: 0,
    recordNumber: 5
}

function handelCurrentChange(val) {
    // 0, 5, 10
    let start = (val - 1) * page.recordNumber
    // 5, 10
    let end = val * page.recordNumber

    effectBlockPage.value = effectBlocksAll.value.slice(start, end)
}

// MAPGIS空间分析
const resultBaseUrl = 'gdbp://MapGisLocal/wuhan/sfcls'
let resultLayerUrl = null
// let anaLayer = null
function clipByPolyAnalysis(strPos) {
    clearA(); //清除之前的分析结果
    //显示进度条
    startPressBar();
    var resultname = resultBaseUrl + "/clipByPolyAnalysisResultLayer" + getCurentTime();
    //实例化ClipByPolygon类
    var clipParam = new Zondy.Service.ClipByPolygon({
        ip: "localhost",
        port: "6163"    //访问IGServer的端口号，.net版为6163，Java版为8089
    });
    //设置被裁剪图层URL
    clipParam.srcInfo = "gdbp://MapGisLocal/wuhan/sfcls/居民区";
    //设置结果URL	
    clipParam.desInfo = resultname;
    //多边形点坐标串
    clipParam.strPos = strPos;
    //调用基类的execute方法，执行多边形裁剪分析。AnalysisSuccess为结果回调函数
    clipParam.execute(AnalysisSuccess, "post", false, "json", AnalysisError);
}

//分析失败回调
function AnalysisError(e) {
    //停止进度条
    stopPressBar();
}
//分析成功后的回调
function AnalysisSuccess(data) {
    //停止进度条
    stopPressBar();
    if (!data.results) {
        alert("裁剪分析失败，请检查参数！");
    }
    else {

        resultLayerUrl = data.results[0].Value || data.results[0].value;

        //将结果图层添加到地图视图中显示
        anaLayer = new Zondy.Map.GdbpLayer("MapGIS IGS ClipAnalysisResultLayer", [resultLayerUrl], {
            ip: "localhost",
            port: "6163",    //访问IGServer的端口号，.net版为6163，Java版为8089,
            isBaseLayer: false
        });
        console.log(anaLayer);
        map.addLayer(anaLayer);
        getBlock()
    }
}
//清除客户端分析结果信息
function clearA() {
    //停止进度条
    stopPressBar();
    if (anaLayer) {
        map.removeLayer(anaLayer);
    }
}
let loading = null
//停止进度条
function stopPressBar() {
    loading?.close()
}
//开始进度条动画
function startPressBar() {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
}








</script>

<style lang="scss">
#notice-btn-brash {
    position: absolute;
    top: 100px;
    left: 50px;
    z-index: 99;
}

#notice-btn-show-dialog {
    position: absolute;
    top: 150px;
    left: 50px;
    z-index: 99;
}

::v-deep .el-dialog__header {
    background-color: #474df1 !important;
    margin: 0;
}

#notice-dialog {
    border-radius: 6px;

    header {
        margin-right: 0;
        background-color: #474df1;
        padding-top: 6px;
        border-radius: 6px 6px 0 0;

        span {
            color: white;
        }

        button {
            top: -4px;
        }
    }

    footer {
        text-align: center;

        button {

            color: black;

            &:first-child {
                border: none;
                background-color: aqua;
            }
        }
    }

    >div {
        padding-bottom: 0;
    }

}
</style>